package com.jt.www.job.woxuebao;

import com.jt.www.admin.order_wxb.service.BatchInsService;
import com.jt.www.dao.mapper.woxuebao.InsBatchEntityMapper;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.enums.woxuebao.ConFirmStatusEnum;
import com.jt.www.enums.woxuebao.HandlerStatusEnum;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.vo.woxuebao.ConfirmAmountVo;
import com.jt.www.model.woxuebao.InsBatchEntity;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtils;
import com.jt.www.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 我学保批量投保  检查到账确认
 *
 * @author admin_ltf
 * @create 2019-06-30 09:43
 */
@Component
@EnableScheduling
public class CheckBatchInsConfirmAmountTask implements SchedulingConfigurer {
    public static final Logger log = LoggerFactory.getLogger(CheckBatchInsConfirmAmountTask.class);
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long IME_OUT = 300L;
    /**
     * 我学保批量投保  检查到账确认 缓存key
     */
    private static final String BATCH_INS_CONFIRM_LOCK_KEY = "EDU_BATCH_INS_CONFIRM";
    @Autowired
    InsBatchEntityMapper insBatchEntityMapper;
    @Autowired
    InsClient insClient;
    @Autowired
    BatchInsService batchInsService;
    /**
     * 任务开关
     */
    @Value("${jtpf.batchins.confirm.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.batchins.confirm.cron}")
    private String cron;// 每隔2分钟执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        Runnable task0 = () -> checkStart();
        Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
        taskRegistrar.addTriggerTask(task0, trigger0);
    }

    private void checkStart() {
        //多个服务同时启动定时任务，在执行体开始时判断是否有其他线程在执行
        //设置缓存失败表示有在执行的任务
        if (!RedisUtil.setLock(IME_OUT, BATCH_INS_CONFIRM_LOCK_KEY)) {
            return;
        }
        try {
            log.info("我学保批量投保(到账确认)任务开始!");
            process();
        } catch (Exception e) {
            log.info("我学保批量投保(到账确认)任务出错!");
        } finally {
            //删除缓存
            RedisUtil.delete(BATCH_INS_CONFIRM_LOCK_KEY);
            log.info("我学保批量投保(到账确认)任务结束!");
        }
    }

    private void process() {
        // 查询投保成功的，未执行到账确认或执行失败的
        Weekend<InsBatchEntity> weekend = Weekend.of(InsBatchEntity.class);
        WeekendCriteria<InsBatchEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(InsBatchEntity::getHandleStatus, HandlerStatusEnum.SUCCESS_INS.getCode());
        criteria.andEqualTo(InsBatchEntity::getIsDeleted, IsOrNotEnum.NO.getValue());
        criteria.andIn(InsBatchEntity::getConfirmStatus,
                Lists.newArrayList(ConFirmStatusEnum.DEFAULT.getCode(), ConFirmStatusEnum.ERROR.getCode()));
        //重试5次
        criteria.andLessThan(InsBatchEntity::getTimes, 6);
        //从第0位开始查询，查询出前300个
        RowBounds rowBounds = new RowBounds(0, 300);
        List<InsBatchEntity> resultList = insBatchEntityMapper.selectByExampleAndRowBounds(weekend, rowBounds);
        if (CollectionUtils.isNotEmpty(resultList)) {
            for (InsBatchEntity entity : resultList) {
                String findCode = "BATCH_INS_" + entity.getTbNo();
                String currentTime = DateUtils.getCurrentTime();
                List<ConfirmAmountVo> confirmAmountVoList = new ArrayList<>();
                ConfirmAmountVo confirmAmountVo = new ConfirmAmountVo();
                confirmAmountVo.setAfId(entity.getTbNo());
                confirmAmountVo.setAmount(entity.getPrem());
                confirmAmountVo.setConfirmDate(currentTime);
                confirmAmountVo.setCurtype("01");
                confirmAmountVo.setOperator(entity.getUserCode());
                confirmAmountVo.setPayChannel("04");
                confirmAmountVoList.add(confirmAmountVo);
                ResponseEntity<GenericDataResponse<Map<String, Object>>> genericListResponseResponseEntity;
                try {
                    genericListResponseResponseEntity = insClient.confirmAmount(confirmAmountVoList);
                } catch (Exception e) {
                    log.error("{} 批量投保，到账确认，远程调用失败{}", findCode, e);
                    batchInsService.updateConfirmStatusById(entity.getId(), ConFirmStatusEnum.ERROR, entity.getTimes() + 1);
                    continue;
                }
                GenericDataResponse<Map<String, Object>> body = genericListResponseResponseEntity.getBody();
                String code = body.getCode();
                String msg = body.getMsg();
                log.info("{} 远程调用到账确认接口回参:{}", findCode, JsonUtils.toJson(genericListResponseResponseEntity));
                if (GenericDataResponse.CODE_OK.equals(code) || msg.indexOf("重复确认") > -1) {
                    batchInsService.updateConfirmStatusById(entity.getId(), ConFirmStatusEnum.SUCCESS, 0);
                } else {
                    batchInsService.updateConfirmStatusById(entity.getId(), ConFirmStatusEnum.ERROR, entity.getTimes() + 1);
                }
            }
        }
    }

}
